package practice_2025_10.practice_10_22;

class Solution {
    /**
     * 不同的子序列
     * 动态规划
     * @param s
     * @param t
     * @return
     */
    public int numDistinct(String s, String t) {
        int sLen = s.length();
        int tLen = t.length();
        if (sLen < tLen) {
            return 0;
        }
        int[][] dp = new int[tLen + 1][sLen + 1];
        s = " " + s;
        t = " " + t;
        // 初始化
        for(int j = 0; j <= sLen; j++) {
            dp[0][j] = 1;
        }
        for(int i = 1; i <= tLen; i++) {
            for(int j = 1; j <= sLen; j++) {
                if (t.charAt(i) == s.charAt(j)) {
                    dp[i][j] = dp[i - 1][j - 1];
                }
                dp[i][j] += dp[i][j - 1];
                dp[i][j] %=  1000000000 + 7;
            }
        }
        // for(int i = 0; i <= tLen; i++) {
        //     System.out.println(Arrays.toString(dp[i]));
        // }
        return dp[tLen][sLen];
    }

    /**
     * 交错字符串
     * 动态规划
     * @param s1
     * @param s2
     * @param s3
     * @return
     */
    public boolean isInterleave(String s1, String s2, String s3) {
        int len1 = s1.length();
        int len2 = s2.length();
        int len3 = s3.length();
        if (len1 == 0 && len2 == 0 && len3 == 0) {
            return true;
        }
        if (len1 + len2 != len3) {
            return false;
        }
        s1 = " " + s1;
        s2 = " " + s2;
        s3 = " " + s3;
        // dp[i][j]: s1 以 i 结尾字符, 组合 s2 以 j 结尾字符，能否构成 s3 以 i + j 结尾字符
        boolean[][] dp = new boolean[len1 + 1][len2 + 1];
        for(int i = 0; i <= len1; i++) {
            if (s1.charAt(i) == s3.charAt(i)) {
                dp[i][0] = true;
            } else {
                break;
            }
        }
        for(int j = 0; j <= len2; j++) {
            if (s2.charAt(j) == s3.charAt(j)) {
                dp[0][j] = true;
            } else {
                break;
            }
        }
        for(int i = 1; i <= len1; i++) {
            for(int j = 1; j <= len2; j++) {
                dp[i][j] = (s1.charAt(i) == s3.charAt(i + j) && dp[i - 1][j]) ||
                        (s2.charAt(j) == s3.charAt(i + j) && dp[i][j - 1]);

            }
        }
        //     for(int i = 0; i <= len1; i++) {
        //          System.out.println(Arrays.toString(dp[i]));
        //     }
        //    System.out.println(dp[len1][len2] + " " + len1 + " " + len2);
        return dp[len1][len2];
    }
}